package com.example.HelloSpace.service;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.HelloSpace.database.entities.SpaceMissionEntity;
import com.example.HelloSpace.ui.MissionSubscribedView;
import com.example.HelloSpace.viewmodels.SubscribedMissionsViewModel;

import java.time.Instant;
import java.util.List;

public class MissionGenerator {

    public static void generateMissionsView(Context context, LinearLayout container, List<SpaceMissionEntity> missions, SubscribedMissionsViewModel viewModel) {
        container.removeAllViews(); // 清除旧的视图
        for (final SpaceMissionEntity mission : missions) {
            final MissionSubscribedView view = new MissionSubscribedView(context);
            if(mission.isCountingDown){
                updateTextViewWithCountdown(view, mission.launchTimeUtc, viewModel);
            }
            else{
                view.setCountDown(mission.launchTime);
            }
            view.setMissionName(mission.missionName);
            view.setStatusTag(mission.status);
            // 使用Handler每秒更新一次倒计时
            final Handler handler = new Handler(Looper.getMainLooper());
            handler.post(new Runnable() {
                @Override
                public void run() {
                    if(mission.isCountingDown)
                        updateTextViewWithCountdown(view, mission.launchTimeUtc, viewModel);
                    handler.postDelayed(this, 1000); // 每秒执行一次
                }
            });

            container.addView(view);
        }
    }

    private static void updateTextViewWithCountdown(MissionSubscribedView view, Instant launchTimeUtc, SubscribedMissionsViewModel viewModel) {
        String countdown = viewModel.calculateCountdown(launchTimeUtc);
        view.setCountDown(countdown);
    }
}
